package com.ryskoo.customer.vendormanager.repository;

import com.ryskoo.common.constant.CacheConstant;
import com.ryskoo.customer.vendormanager.domain.VendorManagerPO;
import com.ryskoo.framework.core.repository.BasicRedisImpl;
import com.ryskoo.framework.core.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Primary
@Repository("customerVendorManagerRedisImpl")
public class VendorManagerRedisImpl extends BasicRedisImpl<VendorManagerPO> implements IVendorManagerRepository {
	@Autowired
	private RedisUtil redisClient;

	@Autowired
	private IVendorManagerRepository managerRepository;

	@PostConstruct
	public void init() {
		this.setRedisClient(redisClient);
		this.setDao(managerRepository);
	}

	public VendorManagerRedisImpl() {
		super(CacheConstant.PMS_MANAGER_KEY);
	}

	/**
	 * 根据用户名查询管理员信息
	 *
	 * @param userName
	 * @return
	 */
	@Override
	public VendorManagerPO getManagerByLoginName(String userName) {
		// 通过用户名先从缓存获取
		Object object = redisClient.getObject(CacheConstant.PMS_MANAGER_KEY + userName, VendorManagerPO.class);
		if (object != null) {
			return (VendorManagerPO) object;
		}
		// 根据用户名查询管理员uuid
		String uuid = managerRepository.getManagerUuidByLoginName(userName);
		if (!StringUtils.isEmpty(uuid)) {
			VendorManagerPO manager = super.getByUuid(uuid);
			if (manager != null) {
				redisClient.setObject(CacheConstant.PMS_MANAGER_KEY + userName, manager);
				return manager;
			}
		}
		return null;
	}

	/**
	 * 根据用户名查询管理员uuid
	 *
	 * @param userName
	 * @return
	 */
	@Override
	public String getManagerUuidByLoginName(String userName) {
		return managerRepository.getManagerUuidByLoginName(userName);
	}

	/**
	 * 根据 商户uuid和是否超级管理员， 查找对应的员工
	 * 
	 * @param vendorUuids
	 * @param superManager
	 * @return
	 */
	@Override
	public List<VendorManagerPO> getVendorManagerByVendorUuid(List<String> vendorUuids, Boolean superManager) {
		return managerRepository.getVendorManagerByVendorUuid(vendorUuids, superManager);
	}

	@Override
	public List<VendorManagerPO> getManagerByVendorUuidAndType(String vendorUuid, int type) {
		List<VendorManagerPO> list = new ArrayList<>();
		List<String> managerUuids = managerRepository.getUuidsByVendorUuidAndType(vendorUuid,type);
		for (String uuid:managerUuids) {
			VendorManagerPO po = managerRepository.getByUuid(uuid);
			list.add(po);
		}
		return list;
	}

	@Override
	public List<String> getUuidsByVendorUuidAndType(String vendorUuid, int type) {
		return managerRepository.getUuidsByVendorUuidAndType(vendorUuid,type);
	}

	@Override
	public void setNotReceiveNotificationToAll(String vendorUuid,int type,String managerUuid) {
		managerRepository.setNotReceiveNotificationToAll(vendorUuid,type,managerUuid);
	}
}
